/**
 * 这里的配置项及拦截器通常和业务无关
 * 请求拦截器的执行顺序：最后注册--->最先注册
 * 响应拦截器的执行顺序：最先注册--->最后注册--->then|catch
 * 根据顺序做好数据及状态的传递
 */
import qs from 'qs'
import axios from 'axios'
import mergeConfig from 'axios/lib/core/mergeConfig'
import {Loading} from 'element-ui'

let loadingInstance = null

// 全局的 axios 默认值
axios.defaults.baseURL = 'http://localhost:3000'
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

// 请求前拦截（全局)
const requestHandle = config => {
  console.log('全局请求前拦截')
  // 不传递默认开启loading
  if (!config.hideLoading) {
    loadingInstance = Loading.service({
      text: '加载中'
    })
  }

  return config
}
// 请求失败拦截（全局)
const requestErrHandle = err => {
  console.log('全局请求失败拦截')
  throw err
}

/* 响应成功拦截 (全局) */
const responseHandle = res => {
  console.log('全局响应成功拦截')
  // 关闭 loading
  loadingInstance.close()
  return res
}

/* 响应失败拦截 (全局) */
const responseErrHandle = err => {
  console.log('全局响应失败拦截')
  // 关闭loading
  loadingInstance.close()
  throw err
}
/**
 * @description: 创建axios实例
 * @param requestConfig 请求参数
 * @param callbac 创建实例完成后执行
 * @return: axios实例
 */
export const createAxios = (requestConfig, callback) => {
  console.log('reqeustConfig:', requestConfig)
  const defaults = {
    /* 默认配置  */
    /* 修改数组的序列化的方式：  参照 https://github.com/ljharb/qs */
    paramsSerializer: params => qs.stringify(params, {arrayFormat: 'repeat'})
  }
  const instance = axios.create(mergeConfig(defaults, requestConfig))
  instance.interceptors.request.use(requestHandle, requestErrHandle)
  instance.interceptors.response.use(responseHandle, responseErrHandle)
  callback && callback(instance)
  return instance
}

export default createAxios
